package com.kern.rpc.server;

import com.kern.rpc.service.IStudentService;
import com.kern.rpc.service.impl.StudentServiceImpl;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by caoshi at 20:23 2021-07-18
 */
public class RpcServer {

    private static final int CORE_POOL_SIZE = 5;        // 线程池中活跃线程数
    private static final int MAXIMUMPOOL_SIZE = 10;     // 线程池中最大线程数

    // 多余的空闲线程在终止之前等待新任务的最大时间
    private static final int KEEP_ALIVE_TIME = 200;


    // 用于接收客户端连接
    private ServerSocket serverSocket;
    // 连接端口
    private int serverPort;


    public RpcServer(int port) throws IOException {
        this.serverPort = port;
        this.serverSocket = new ServerSocket(this.serverPort);
    }


    public void start() {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(CORE_POOL_SIZE,
                MAXIMUMPOOL_SIZE,
                KEEP_ALIVE_TIME,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10));

        for (; ; ) {
            try {
                Socket socket = serverSocket.accept();
                RpcServerService serverService = new RpcServerService(socket);
                serverService.registerService(IStudentService.class, StudentServiceImpl.class);
                executor.execute(serverService);

            } catch (IOException e) {
                e.printStackTrace();
                //System.exit(0);
            }
        }


    }


}
